package dao;

import hbt.HibernateUtil;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import Dominio.Factura;
import Dominio.ItemFactura;
import Dominio.Rodamiento;


public class FacturaDAO {

	private static FacturaDAO instancia = null;
	private static SessionFactory sf = null;
	private Session session = null;

	public static FacturaDAO getInstancia() {
		if (instancia == null) {
			sf = HibernateUtil.getSessionFactory();
			instancia = new FacturaDAO();
		}
		return instancia;
	}

	private Session getSession() {
		if (session == null)
			session = sf.openSession();
		return session;
	}

	public void closeSession() {
		if (session != null)
			session.close();
	}

	public void crearFactura(Factura f) throws Exception 
	{
		try {
			Session s = getSession();
			s.beginTransaction();			
			s.save(f);
			s.persist(f);
			s.flush();
			s.getTransaction().commit();
			
		} 
		catch (Exception e) 
		{
			session = null;
			throw new Exception("factura");
		}
	}

	public void agregarItemFactura(ItemFactura item) {
		
		Session s = getSession();
		
		Rodamiento r = (Rodamiento)s.get(Rodamiento.class,item.getRodamiento().getId());
		item.setRodamiento(r);
		s.beginTransaction();
		s.persist(item);
		s.flush();
		s.getTransaction().commit();
	}

	public int obtenerUltimoNro() 
	{
		try
		{
			Session s=getSession();
			s.beginTransaction();
			int ultimo = 0;
			int aux = (Integer)s.createQuery("Select max(f.nroFactura) from Factura f").uniqueResult();
			if (aux > 0)
			{	
				ultimo = aux;
			}
			s.flush();
			s.getTransaction().commit();
			return ultimo;
		}
		catch(Exception e)
		{
			return 0;
		}
	}

	public Factura obtenerFactura(int facturaId) 
	{
		try
		{
			Session s=getSession();
			s.beginTransaction();
			
			Factura fac= (Factura)s.createQuery("Select f from Factura f where f.nroFactura = :nro").setParameter("nro", facturaId).uniqueResult();
			s.flush();
			s.getTransaction().commit();
			return fac;
		}
		catch(Exception e)
		{
			return null;
		}

		
	}
}
